package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import server.ForumAPIService;
import server.controller.WebAdapter;

import database.DBHandler;
import database.DatabaseStub;
import forum.Post;

/**
 * Servlet implementation class viewPosts
 */
//@WebServlet("/viewPosts")
public class viewPosts extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public viewPosts() {
		super();
	}

	/**
	 * @see Servlet#init()
	 */
	public void init() throws ServletException {
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("viewPosts. doGet");

		// init session of request
		HttpSession session = request.getSession();
		
		Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");
		String username = (String) session.getAttribute("username");

		if (isLoggedIn != null && isLoggedIn.booleanValue()) {
			int threadID = ((Integer) session.getAttribute("threadID")).intValue();

			ForumAPIService db = WebAdapter.getInstance();
			
			// get all posts
			List<Post> allPosts = ((WebAdapter)db).getThread(threadID, username);

			// set the returned collection in the request
			request.setAttribute("posts", allPosts);
			request.setAttribute("threadID", threadID);

			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/postsPage.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
		} else {// not logged in

			request.setAttribute("errorMsg", "Please Log In");
			String addr = "http://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath();

			request.setAttribute("errorLink", addr);
			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/Error.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
